package com.rzico.sbl.ui.report

import android.widget.ImageView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportBookBinding
import com.rzico.sbl.model.ReportGoodsData
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.viewmodel.ReportViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.ActivityStack
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class ReportBookActivity : BaseActivity(R.layout.activity_report_book) {

    private val mBinding by lazy { ActivityReportBookBinding.bind(getRootView()) }

    private var mOrderSn = ""       //订单编号
    private var mCoupon = ""        //优惠券一
    private var mVip = ""           //优惠券二
    private var mExchange = ""      //优惠券三
    private var mFreightMemo = ""   //运费小计
    private var mFreightPaid = ""   //已付运费
    private var mFreightUnpaid = "" //未付运费
    private var mAmount = ""        //应收金额
    private var mPrestore = 0       //预存空桶

    override fun getViewModel() = get<ReportViewModel>()

    override fun initData() {
        initTitle(title = "订单确认")

        initLayout()

        intent.getExtra("orderSn")
            .apply {
                mOrderSn = this
                notEmpty {
                    mBinding.btSure.text = "修改订单"
                }
            }

        getData()
    }

    private fun initLayout() {
        mBinding.bookList.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())

            addItemDecoration(
                SpaceTBDecoration(
                    top = 5f,
                    hasHeader = false,
                    hasFooter = false,
                    spaceColor = R.color.white
                )
            )

            mAdapter = SlimAdapter.creator()
                .register<ReportGoodsData>(R.layout.item_order_detail_list) { jector, bean, _ ->
                    jector.apply {
                        gone(R.id.item_order_type_ll)
                        text(R.id.item_order_name, bean.name)
                        text(R.id.item_order_price, "单价: ${bean.phPrice.formatDecimal()}元")
                        text(R.id.item_order_num, "x${bean.quantity}")

                        with<ImageView>(R.id.item_order_img) {
                            it.loadImage(bean.thumbnail)
                        }
                    }
                }
                .attachTo(this)
        }
    }

    override fun initListener() {
        mBinding.apply {
            bookFeeAll.oneClick {
                it.gone()
                bookFeeExpand.expand()
            }

            btSure.oneClick {
                when {
                    bookPrestore.text.isNotEmpty()
                            && bookPrestore.textInt > mPrestore -> {
                        showToast("当前预存空桶不足，请重新输入")
                        return@oneClick
                    }
                }

                mList.notEmpty {
                    getViewModel()
                        .goodsSubmit(
                            ReportUrl.getBaseUrl().reportSub,
                            "sn" to mOrderSn,
                            "body" to intent.getExtra("body"),
                            "couponDiscount" to mCoupon,
                            "vipDiscount" to mVip,
                            "exchangeDiscount" to mExchange,
                            "amount" to mAmount,
                            "memo" to "${bookHint.content}|${bookMemo.textTrim}",
                            "freightPayable" to mFreightUnpaid,
                            "freightPaid" to mFreightPaid,
                            "freightMemo" to mFreightMemo,
                            "adAdvanceStock" to bookPrestore.textInt
                        )
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeBySuccess(
                            event = getViewModel(),
                            onSuccess = {
                                mOrderSn
                                    .isEmpty()
                                    .conditionElse(
                                        actionTrue = {
                                            showToast("订单提交成功！")

                                            val listId = ArrayList<String>()
                                            listId.add("done")
                                            mList.forEach {
                                                it as ReportGoodsData
                                                listId.add(it.id)
                                            }
                                            LiveEventBus
                                                .get("carList")
                                                .post(listId.joinToString(","))

                                            ActivityStack.screenManager.popActivities(
                                                ReportBookActivity::class.java,
                                                ReportCarActivity::class.java
                                            )
                                        },
                                        actionFalse = {
                                            showToast("订单修改成功！")

                                            // 采购单刷新
                                            LiveEventBus
                                                .get("buyOrderModify")
                                                .post("refresh")
                                            // 报货订单刷新
                                            LiveEventBus
                                                .get("orderModify")
                                                .post("refresh")

                                            ActivityStack.screenManager.popActivities(
                                                ReportBookActivity::class.java,
                                                ReportCarActivity::class.java,
                                                ReportGoodsActivity::class.java
                                            )
                                        }
                                    )
                            }
                        )
                }
            }
        }
    }

    /**
     * 订单提交信息
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsCreate(
                ReportUrl.getBaseUrl().reportCrt,
                mOrderSn,
                intent.getExtra("body")
            )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mFreightMemo = obj.optNotNull("freightMemo")
                    mFreightPaid = obj.optNotNull("freightPaid")
                    mFreightUnpaid = obj.optNotNull("freightPayable")
                    mCoupon = obj.optNotNull("couponDiscount")
                    mVip = obj.optNotNull("vipDiscount")
                    mExchange = obj.optNotNull("exchangeDiscount")
                    mAmount = obj.optNotNull("amountPayable")
                    mPrestore = obj.optNotNull("adAdvanceStock").intValue

                    mBinding.apply {
                        bookHint.text =
                            obj.optNotNull("summary")
                                .replace(";\n", ";")
                                .replace(";", ";\n")

                        mCoupon.also {
                            (it.intValue != 0)
                                .condition {
                                    bookCoupon1Ll.visible()
                                    bookCoupon1.text =
                                        "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                }
                        }

                        mVip.also {
                            (it.intValue != 0)
                                .condition {
                                    bookCoupon2Ll.visible()
                                    bookCoupon2.text =
                                        "–${(it.intValue * 0.3).formatDecimal()}元 ($it * 0.3)"
                                }
                        }

                        mExchange.also {
                            (it.intValue != 0)
                                .condition {
                                    bookCoupon3Ll.visible()
                                    bookCoupon3.text =
                                        "–${(it.intValue * 2.0).formatDecimal()}元 ($it * 2.0)"
                                }
                        }

                        obj.optNotNull("freight")
                            .also {
                                (mFreightPaid.doubleValue == 0.0
                                        && mFreightUnpaid.doubleValue == 0.0
                                        && it.doubleValue > 0)
                                    .condition {
                                        bookFee1Ll.gone()
                                        bookFeeLl.visible()
                                        bookFee.text = "+${it.formatDecimal()} 元"
                                    }
                            }

                        bookPrice.text = "${mAmount.formatDecimal()} 元"

                        ((mFreightPaid.doubleValue > 0
                                || mFreightUnpaid.doubleValue > 0))
                            .condition {
                                bookFee1Ll.visible()
                                bookFeeLl.gone()

                                bookFee1Hint.text =
                                    mFreightMemo
                                        .replace(";\n", ";")
                                        .replace(";", ";\n")

                                bookFeePaid.text = "${mFreightPaid.formatDecimal()} 元"
                                bookFeeUnpaid.text = "${mFreightUnpaid.formatDecimal()} 元"
                            }

                        // 预存空桶
                        bookStore.text =
                            mPrestore.also {
                                bookStoreLl.isVisible = it > 0
                            }.toString()
                    }

                    // 商品列表
                    val objOrder = obj.optJSONArray("goodsList") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            ReportGoodsData::class.java
                        )
                    )
                    mAdapter.setDataList(mList)

                    var count = 0
                    var amount = 0.0
                    mList.forEach {
                        it as ReportGoodsData
                        count += it.quantity.intValue
                        amount += it.phPrice.doubleValue * it.quantity.intValue
                    }

                    mBinding.bookTotal.text = count.toString()
                    mBinding.bookAmount.text = amount.formatDecimal()
                }
            )
    }

}